from sqlalchemy import Column, String, DateTime, Boolean
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database.base import Base
import uuid

class User(Base):
    __tablename__ = "users"
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    username = Column(String(50), unique=True, nullable=False, index=True)
    email = Column(String(255), unique=True, nullable=False, index=True)
    full_name = Column(String(255))
    password_hash = Column(String(255), nullable=False)
    role = Column(String(20), default="viewer", nullable=False)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    devices = relationship("Device", back_populates="owner")
    
    # 维护记录相关关系
    assigned_maintenances = relationship("MaintenanceRecord", foreign_keys="MaintenanceRecord.assigned_to", back_populates="assigned_user")
    performed_maintenances = relationship("MaintenanceRecord", foreign_keys="MaintenanceRecord.performed_by", back_populates="performed_user")
    approved_maintenances = relationship("MaintenanceRecord", foreign_keys="MaintenanceRecord.approved_by", back_populates="approved_user")
    created_maintenances = relationship("MaintenanceRecord", foreign_keys="MaintenanceRecord.created_by", back_populates="creator")
    
    # 维护计划相关关系
    assigned_plans = relationship("MaintenancePlan", foreign_keys="MaintenancePlan.default_assignee", back_populates="default_assignee_user")
    created_plans = relationship("MaintenancePlan", foreign_keys="MaintenancePlan.created_by", back_populates="creator")